<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html> 
<!--[if lt IE 7 ]><html class="ie ie6"><![endif]-->
<!--[if IE 7 ]><html class="ie ie7"><![endif]-->
<!--[if IE 8 ]><html class="ie ie8"><![endif]-->
<!--[if IE 9 ]><html class="ie ie9"><![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--><html><!--<![endif]-->
<head>
	<meta charset="utf-8">
	<meta name="renderer" content="webkit" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="initial-scale=1,minimum-scale=1" />
	<title>活动管理</title>
	<c:import url="${appRoot}/public/head-tag.jsp"/>
	<style type="text/css">
		.table-lottery td{
			padding:5px;
		}
		.textarea{
			width:100%;
			min-width:300px;
			min-height:150px;
			border:0;
		}
		.xiuxiu-upload-container,div.xiuxiu-upload  {
			width: 310px;
			height: 130px;
		}
		.text-datetime{
			width:134px;
		}
		.row-value{
		    display:block;
		}
		.choose-action{
		    margin-left:15px;
		}
	</style>
</head>
<body>

    <c:import url="${appRoot}/public/header.jsp"/>
    
    <section class="container" id="app">
    
		<c:set var="sidebar" scope="request" value="content"/>
		<c:set var="navbar" scope="request" value="activity"/>
		<c:import url="${appRoot}/public/sidebar.jsp"/>
		
    	<div class="content">
    		<div class="content-top">
    			<h3 class="content-title">
    				<div class="bread">
    					<a href="/Manager/web/action/listPage">活动管理</a>
    					<span>&gt;</span>
    					
    					<template v-if="isEdit">
        					<span v-text="appTitle+'活动编辑'"></span>
    					</template>
    					
    					<template v-else>
        					<a href="/Manager/web/action/guide">活动发布</a>
        					<span>&gt;</span>
        					<span v-text="appTitle"></span>
    					</template>
    					
    				</div>
    			</h3>
    		</div>
    		<div class="content-main">
    			<div class="block block-main">
    				<div class="block-content" >

						<form action="{{submitAction}}" method="post" goback="/Manager/web/action/listPage">
							<div class="form-block">
								<div class="form-row">
									<span class="row-label">活动标题：</span>
									<div class="row-content">
										<input name="title" type="text" class="text"   ipattern="^.{2,40}$" iname="活动标题" v-model="form.title"/>
									</div>
								</div>
								
								<div class="form-row">
									<span class="row-label">活动时间：</span>
									<div class="row-content">									 	
										<input type="text" name="sdate" lazy  v-model="form.applyStartTime | formatDate" class="text text-datetime" datepicker="datetime" iname="活动起始时间" itip="请选择活动起始时间" placeholder="活动起始时间" />
										<span>~</span>
										<input type="text" name="edate" lazy  v-model="form.applyEndTime | formatDate"  class="text text-datetime" datepicker="datetime" iname="活动结束时间" itip="请选择活动结束时间" placeholder="活动结束时间" />
									</div>
								</div>
								
								<div class="form-row">
                                    <span class="row-label">抽奖资格：</span>
                                    <div class="row-content">
                                        <div class="row-value">
                                            <input type="radio" id="limit-0" name="limits" value="0"  v-model="form.limits" :true-value="0"/>
                                            <label for="limit-0">不限</label>
                                        </div>
                                        <div class="row-value">
                                            <input type="radio" id="limit-1" name="limits" value="1"  v-model="form.limits"  :true-value="1"/ >
                                            <label for="limit-1">限报名用户</label>
                                            <template v-if="form.limits==1">
                                                <span v-if="form.actionPrize.relation_info">
                                                       : 参加过【<a href="javascript:;" @click="chooseAction"  v-text="form.actionPrize.relation_info" class="action-link"></a>】的用户
                                                </span>
                                                <span v-else>
                                                       <a @click="chooseAction"  href="javascript:;" class="action-link">选择活动</a>
                                                </span>
                                                <input type="hidden" iname="关联活动" irequired="true" v-model="form.actionPrize.relation_id"  name="relationid"/>
                                            </template>
                                        </div>
                                    </div>
                                </div>

                                <div class="form-row">
									<span class="row-label">设置轮播：</span>
									<div class="row-content">
										<div class="row-value">
											<input type="checkbox" name="istop" id="category_2" value="1" v-model="form.loopStatus" :true-value="1"/>
											<label for="category_2">设置为轮播</label>
										</div>
									</div>
								</div>
                                
                                
                                <div class="form-row">
                                    <span class="row-label">抽奖次数：</span>
                                    <div class="row-content">
                                        <input name="availabletimes" type="text" class="text"   placeholder="没有抽奖上限请填写-1"  iname="抽奖次数" v-model="form.actionPrize.available_times"/>次/每天
                                    </div>
                                </div>

                                <div class="form-row">
                                    <span class="row-label">奖品设置：</span>
                                    <div class="row-content">
                                        <div lottery-editor>
                                            <textarea type="config" v-model="form.actionPrizeInformationItems | json" style="display:none;"></textarea>
                                        </div>
                                    </div>
                                </div>

								<div class="form-row">
									<span class="row-label">活动图片：</span>
									<div class="row-content">
										<div  xx-upload  class="xiuxiu-upload-container">
											<textarea type="config" style="display:none;">{{getImageConfig(form.thumb) | json}}</textarea>
										</div>
										<p class="value-note">图片规格：750x360</p>
									</div>
								</div>

								<div class="form-row">
									<span class="row-label">介绍：</span>
									<div class="row-content">
										<textarea name="intro" rteditor class="textarea" iname="活动介绍"   v-model="form.intro"></textarea>
									</div>
								</div>

								<div class="form-row form-row-btn">
									<div class="row-content">
										<input type="hidden" name="type" value="{{pageType}}">
										<input type="hidden" name="appId" value="{{appId}}">
										<input type="hidden" v-if="isEdit" name="id" v-model="form.actionId">
										<button class="btn btn-default btn-large" v-text="form.actionId?'保存修改':'确认添加'">确认提交</button>
									</div>
								</div>
							</div>
						</form>
    				</div>
    			</div>

    		</div>
    	</div>
    </section>
    
    <script type="text/template" id="field/editor">
        <ul>
            <li v-for="item in list">
                <span class="item">
                    <input type="text" class="text" v-model="item.title" lazy @keydown.enter.prevent="addField({isNeeded:1})"  placeholder="输入报名项目名称" iname="项目名称" ipattern="^.{1,60}$" v-bind:value="item.title"/>
                    <a href="javascript:;" @click="removeField(item.id)" class="action-link action-remove">删除-</a>
                </span>
                <span>
                    <label><input type="checkbox"  v-model="item.isNeeded"  :true-value="1"  :false-value="0" />必填项</label>
                </span>
                <span>
                    <select v-model="item.type" class="select">
                     <option value="">请选择控件类型</option>
                     <option value="1">文本输入框</option>
                     <option value="2">多行输入框</option>
                     <option value="3">数量选择框</option>
                    </select>
                    <input 
                        v-if="item.type==3"
                        type="text" 
                        class="text text-100" 
                        lazy 
                        v-model="item.maxnumber" 
                     placeholder="报名最大人数" iname="报名最大人数" ipattern="^\d{1,2}$" v-bind:value="item.maxnumber"/>
                </span>
            </li>
            <input type="hidden" name="items" value="{{list | json 0}}"/>
            <template v-if="list.length<config.max">
                <li>
                    <a href="javascript:;" @click="addField({isNeeded:1})" class="action-link">+添加项目</a>
                </li>
            </template>
        </ul>
	</script>
	
    <script type="text/template" id="lottery/editor" title="奖项编辑器">
        <div class="row-value align-left">
            {{if data && data.length < max}}
            <a href="javascript:;" action="lottery.item.add" class="action-link">添加奖项+</a>
            {{else}}
            <a href="javascript:;" class="action-link">最多添加<b>{{max}}</b>个奖项</a>
            {{/if}}
            {{if data && data.length < min}}
            <input type="hidden" name="_checker" value="1"  ipattern="test" iname="奖项" itip="请添加至少{{min-data.length}}个奖项"/>
            {{/if}}
        </div>
        <table class="table table-lottery align-center">
            <thead>
            <tr>
                <th class="align-left">#</th>
                <th class="align-left">奖项</th>
                <th class="align-left">奖品</th>
                <th class="align-right">概率(%)</th>
                <th>剩余数量/总数</th>
                <th class="align-right">操作</th>
            </tr>
            </thead>
            <tbody>
            {{if !data || !data.length}}
            <tr>
                <td colspan=5 class="align-left">请添加至少<b>{{min}}</b>个奖项</td>
            </tr>
            {{/if}}
            {{each data}}
            <tr>
                <td class="align-left">
                    <p>{{$index+1}}</p>
                </td>
                <td class="align-left">
                    <p>{{$value.name}}</p>
                </td>
                <td class="align-left">
                    <p>{{$value.info}}</p>
                </td>
                <td class="align-right" style="padding-right: 15px;">{{$value.winningprobability}}</td>
                <td>{{$value.count-$value.winningnumber}}/{{$value.count}}</td>
                <td class="align-right">
                    <a action="lottery.item.edit" data-params="{{$value | toJSON}}" href="javascript:;" class="action-link">编辑</a>
                </td>
            </tr>
            {{/each}}
            </tbody>
            <tfoot class="fn-hide">
            <tr>
                <td colspan=3 class="align-right" style="padding-right: 10px;">
                    总概率：<span>{{data | pluck:'winningprobability' | totalProbability}}%</span>
                </td>
                <td colspan=2>
                    <input type="hidden" name="lottery" value="{{data |  toJSON}}" />
                </td>
            </tr>
            </tfoot>
        </table>
    </script>

    <script type="text/template" id="lottery/add" title="添加奖项">
        <form>
            <div class="form-row">
                <span class="row-label">奖项名称：</span>
                <div class="row-content">
                    <input type="text" class="text" name="name"  value="{{name}}" ipattern="^.{1,20}$" iname="奖项名称"/>
                </div>
            </div>
            <div class="form-row">
                <span class="row-label">奖品：</span>
                <div class="row-content">
                    <input type="text" class="text" name="info"  value="{{info}}" ipattern="^.{1,40}$" iname="奖品详细信息"/>
                </div>
            </div>
            <div class="form-row">
                <span class="row-label">奖品数量：</span>
                <div class="row-content">
                    <input type="text" class="text" name="count"  value="{{count}}" ipattern="^\d+$"  iname="奖品数量"/>
                    <span class="text-suffix">个</span>
                </div>
            </div>
            <div class="form-row">
                <span class="row-label">中奖概率：</span>
                <div class="row-content">
                    <input type="text" class="text" name="winningprobability"  value="{{winningprobability}}" ipattern="^\d{1,2}(\.\d+)?$"  iname="中奖概率"/>
                    <span class="text-suffix">%</span>
                    <p class="value-note">请填写0-100范围内的数字</p>
                </div>
            </div>
            <input type="hidden" value="{{winningnumber || 0}}" name="winningnumber"/>
        </form>
    </script>

    <script type="text/template" id="lottery/edit" title="修改奖项">
        <form>
            <div class="form-row">
                <span class="row-label">奖项名称：</span>
                <div class="row-content">
                    <input type="text" class="text" name="name"  value="{{name}}"  ipattern="^.{1,20}$"  iname="奖项名称"/>
					<p class="value-note">如：一等奖二等奖...</p>
                </div>
            </div>
            <div class="form-row">
                <span class="row-label">奖品信息：</span>
                <div class="row-content">
                    <input type="text" class="text" name="info"  value="{{info}}" ipattern="^.{1,40}$" iname="奖品信息"/>
                </div>
            </div>
            <div class="form-row">
                <span class="row-label">奖品数量：</span>
                <div class="row-content">
                    <input type="text" class="text" name="count"  value="{{count}}" ipattern="^\d+$"  iname="奖品数量"/>
                    <p class="value-note">如果不是中奖项请填写0</p>
                </div>
            </div>
            <div class="form-row">
                <span class="row-label">中奖概率：</span>
                <div class="row-content">
                    <div class="com-input">
                        <input type="text" class="text" name="winningprobability"  value="{{winningprobability}}" ipattern="^\d{1,2}(\.\d+)?$"  iname="中奖概率"/>
                        <span class="com-input-suffix">%</span>
                    </div>
                </div>
            </div>
            <!--<div class="form-row">
                <span class="row-label">中奖次数：</span>
                <div class="row-content">
                    <input type="text" class="text" name="limits"  value="{{limits || 0}}" ipattern="^\d+$"  iname="中奖限制"/>
                    <p class="value-note">最多中奖次数，不限制请填0</p>
                </div>
            </div>-->
            <input type="hidden" value="{{winningnumber || 0}}" name="winningnumber"/>
            <input type="hidden" name="id" value="{{id}}" />
        </form>
    </script>
    
    <script type="text/template" id="content/item/select" title="选择">
        <style>
            .block-item-select .content-item-block{
                height:250px;
                overflow-y:scroll;
            }
        </style>
        <section class="content-block block-item-select">
            <div class="content-item" data-template="content/list/item">
                <div class="content-item-top">
                    <form action="{{api}}" method="get" autocomplete="off">
                        <select name="actionType" class="select">
							<option value="">所有活动</option>
							{{each pluginTypes as item}}
							<option value="{{item.value}}">{{item.name}}</option>
							{{/each}}
						</select>
                        <input placeholder="输入关键字搜索" type="text" name="title" class="text"/>
                        <input type="submit" class="btn btn-default" value="搜索" />
                    </form>
                </div>
                <div class="content-item-block scrollbar">
                    <table class="table">
                        <thead>
                            <tr>
                                <th style="width:90%"></th>
                                <th style="width:10%"></th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td colspan="2" class="align-center">
                                    <div class="loading">加载中...</div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </section>
    </script>
    
    <script type="text/template" id="content/list/item">
        {{if  !code }}
            <tr><td colspan="2">请求错误！</td></tr>
        {{else if code!=200}}
            <tr><td colspan="2">{{msg || '查询错误！'}}</td></tr>
        {{else if !data.list || data.list.length==0}}
            <tr><td colspan="2">没有记录！</td></tr>
        {{else}}
            {{each data.list as item}}
                <tr>
                    <td class="align-left">
                        <input id="item_{{item.id || item.actionId}}" data-params="{{item | pick:'actionId:id,title:name' | toJSON}}" value="{{item.id || item.actionId}}" type="radio" name="content_item" />
                        <label for="item_{{item.id || item.actionId}}">【{{item.actionType | getPluginName}}】{{item.title}}</label>
                    </td>
                </tr>
            {{/each}}
        {{/if}}
    </script>
              
              
   <script src="/pages/assets/js/require.all.js"></script>
   <script>
        requirejs([
            'vue',  
            'artDialog',  
            'artTemplate', 
            'moment',
            
            'utils.search',
            'vender.modal', 
            'vender.types', 
            
            'vender.xxupload', 
            'vender.rteditor', 
            'vender.datetimepicker', 
            'vender.actions', 
             
            'jquery.formcheck', 
            'jquery.ajaxsubmit',
            'jquery.common'
        ],
        function(Vue, dialog, template, moment, Search,  Modal, Field, XXUpload, RichTextEditor, DateTimePicker, Action){
        	
        	var search = new Search().getParams();
        	
            var isEdit = !!search.id;
            
            Action.extend({
        		'form.detail' : '/Manager/web/action/detail?id={id}',
        		
        		'form.add' : '/Manager/web/action/addSave',
        		'form.update' : '/Manager/web/action/updateSave',
        		
        		'list.activity':'/Manager/web/action/listSearch?status=1',
            })
            
            template.helper('getPluginName' ,function(t){
                var plugin = Field.Plugins.get(t);
                if(!plugin) return '未知类型';
                return plugin.name
            })
            
            var PageType = Field.Plugins.LOTTERY_WHEEL;
            
   			var App={
   					
    			alert : function(){
    				//return Modal.alert.apply(this, arguments)
    				alert(arguments[0]);
    			},
    			
                getFormData :function(){
                    
                    var dtd = $.Deferred();
                    
                    var defaultData ={
                        limits:0,
                    	actionPrizeInformationItems:[]
                    }
                    
                    if(!isEdit){
                         return dtd.resolve(defaultData);
                    }
                    
                    var url = Action.get('form.detail', search);
                    $.getJSON(url, function(result){
                        var code = result.code;
                        if(code==200){
                            dtd.resolve(result.data)
                        }else{
                            var msg = result.msg || '数据获取失败！';
                            dtd.reject(msg)
                        }
                    })
                    .fail(function(e, type, msg){
                        dtd.reject(type + msg)
                    })
                    return dtd;
                },
                
                chooseContentItem:function(){
                    
                    var dtd = $.Deferred();
                    
                    var id="content/item/select";
                    
                    var title=document.getElementById(id).title;
                    var data={
                        pluginTypes:Field.Plugins.list(),
                        api:Action.get('list.activity')
                    }
                    
                    var content=template(id, data);
                    var idialog=dialog({
                        id : id,
                        title:title,
                        content:content,
                        onshow:function(){
                            this.getContent().find('[data-template]').ajaxLoad({
                                dataFilter:function(res){
                                    return res
                                }
                            })
                        },
                        onclose:function(){
                            dtd.reject();
                            this.remove();
                        },
                        zIndex: 5,
                        width:500,
                        button:[
                            {
                                id:"cancel",value:"取消"
                            },
                            {
                                id:"ok",value:"确定",
                                autofocus:true,
                                callback:function(){
                                    var $input=this.getContent().find("input:checked");
                                    if(!$input.length) {
                                        alert('请选择！')
                                        return false;
                                    }
                                    var params = $input.data('params');
                                    dtd.resolve(params)
                                }
                            }
                        ]
                    }).showModal();
                    
                    return dtd;
                },
    			
    			initForm:function(formData){
    			    var app = this;
    				var fieldEditor = Vue.extend({
                        template:document.getElementById('field/editor').innerHTML,
                        props:['list'],
                        computed:{
                            'list':function(){
                                return this.getStore().list
                            },
                            'config':function(){
                                return this.getStore().config
                            }
                        },
                        data:function(){
                            return this.getInitData();
                        },
                        methods:{
                            getInitData:function(){
                                return {
                                    store:{
                                        config:{
                                           max:12
                                        },
                                        list:this.list
                                    }
                                }
                            },
                            getStore:function(){
                                return this.store;
                            },
                            getID:function(item){
                                return Math.random()*10;
                            },
                            addField:function(data){
                                var id=this.getID();
                                var d=data || {};
                                d.id=id;
                                this.getStore().list.push(d);
                                this.$nextTick(function () {
                                    $(this.$el).find('input:text:last').focus();
                                })
                            },
                            removeField:function(id){
                                this.getStore().list=this.getStore().list.filter(function(d){
                                    return d.id!=id;
                                })
                            }
                        }
                    })
    				
    				new Vue({
    					el:'#app',
    					components:{
    					  'field-editor':fieldEditor
    					},
    					computed:{
    						'form':function(){
    							return this.getStore().form;
    						},
    						'isEdit':function(){
    							return isEdit;
    						},
    						'submitAction' : function(){
    						    if(isEdit) return Action.get('form.update')
    						    return Action.get('form.add')
    						},
    						'pageType':function(){
    							return PageType;
    						},
    						'appTitle' : function(){
    						    return PageType.name
    						}
    					},
    					filters:{
    						formatDate :function(date, format){
    							if(!date) return;
    							format = format || 'YYYY-MM-DD HH:mm';
    							return moment(date).format(format)
    						}
    					},
    					methods:{
    						
    						getInitData :function(){
    						    
    						    formData.limits=function(data){
    						        if(!data.actionPrize || !data.actionPrize.relation_info) return 0;
    						        return 1;
    						    }(formData)
    						    
    							return {
    								store:{
    									form:formData
    								},
    								Field:Field
    							}
    						},
    						
    						getStore :function(){
    							return this.store;
    						},
    						
    						updateStore(keypath, value){
    						    this.$set('store.'+keypath, value)
    						},
    						
    						getImageConfig:function(value){
    							return {
									name:'thumb',
									checker:{
										iname:'活动图片',
										itip:'请上传活动图片'
									},
									value:value
								}
    						},
    						
    						chooseAction:function(){
    						    var that = this;
    						    app.chooseContentItem().then(function(data){
    						        that.updateStore('form.relationid', data.id)
    						        that.updateStore('form.actionPrize.relation_id', data.id)
    						        that.updateStore('form.actionPrize.relation_info', data.name)
    						    })
    						}
    					},
    					data:function(){
    						return this.getInitData()
    					}
    				})
    				
					$("form").ajaxSubmitify({
						beforeSubmit:function(){
							
							//检查图片是否已上传
							// TODO
						}
					})
    			},
    			
    			initAll : function(){
                    
                    XXUpload('[xx-upload]',{size:'750:360'});
                    
                    DateTimePicker('[datepicker]');
                
                    RichTextEditor('[rteditor]');
                    
					this.initLotteryEditor();
    			},
    			
    			init:function(){
    				var app = this;
    				
    				//$('body').loading(true)
	   				
    				this.getFormData()
    				.then(function(data){
    				    
    					app.initForm(data);
    					app.initAll();
    				})
    				.fail(function(msg){
    					app.alert(msg)
    				})
    				.always(function(){
		   				//$('body').loading(false)
    				})
    			}
    		}
			
            // 奖项编辑器
            $.extend(App,{
                initLotteryEditor:function(){

                    // 计算总概率
                    template.helper('totalProbability',function(list){
                        var totalProbability= Number((new Function('return '+list.join('+'))() || 0).toFixed(2));
                        return totalProbability;
                    });

                    template.helper('addAttr',function(obj,attr,value){
                        if(Object.prototype.toString.apply(obj)==='[object Object]') {
                            obj[attr]=value;
                        }
                        return obj;
                    });

                    template.helper('transformData',function(obj){
                        if(Object.prototype.toString.apply(obj)==='[object Array]') {
                            obj = obj.map(function(value,i){
                                value.prizeid=i+1;
                                delete value.id;
                                return value;
                            })
                        }
                        return obj;
                    });

                    var LotteryEditor=function(el,options){
                        return this.init(el,options)
                    }

                    LotteryEditor.prototype={

                        init:function(el,options){
                            this.el=el;
                            this.$el=$(el);

                            var defaults={
                                max:12,
                                min:6
                            };

                            this.options=$.extend({},defaults,options);
                            this.data=[];

                            this.addItem(this.options.data,false);

                            //this.data=this.options.data;
                            this.initEvents();
                            this.render();
                            return this;
                        },

                        initEvents:function(){
                            var that=this;
                            var actions=this.options.actions;
                            this.$el.on('click',function(e){
                                var $target=$(e.target);
                                var action=$target.attr('action');
                                var regex=/^lottery\.item\.(\w+)$/;
                                if(regex.test(action)){
                                    var fnName=regex.exec(action)[1];
                                    var fn=actions[fnName];
                                    if(typeof fn==='function'){
                                        var data=$target.data('params');
                                        fn.call(that,data);
                                    }
                                }
                            })
                        },

                        render:function(){
                            var list=this.data;
                            var renderData = $.extend({data:list},this.options.config);

                            var html =  this.options.template(renderData);
                            this.$el.html(html);
                        },

                        _keys:{},
                        hasItem:function(id){
                            return id in this._keys;
                        },
                        isPlainObject:function(o){
                            return Object.prototype.toString.apply(o)==='[object Object]';
                        },
                        isArrayObject:function(o){
                            return Object.prototype.toString.apply(o)==='[object Array]';
                        },
                        createId:function(){
                            var id=parseInt(Math.random() * 10000000);
                            if(id in this._keys) return this.createId();
                            this._keys[id]=id;
                            return id;
                        },

                        addItem:function(item,render){
                            var that=this;

                            if(this.isArrayObject(item)){
                                item.forEach(function(value,i){
                                    that.addItem(value,render);
                                })
                                return;
                            }

                            if(!this.isPlainObject(item)) throw new Error('invalid Object!');

                            var theItem=item;

                            if(!theItem.id) {
                                theItem.id = this.createId();
                            }

                            else if(this.hasItem(theItem.id)){
                                this.removeItem(theItem.id,false);
                            }

                            this.data.push(theItem);
                            this._keys[theItem.id]=theItem.id;

                            if(render!==false){
                                this.render();
                            }
                        },

                        updateItem:function(item){
                            this.data = this.data.map(function(o,i){
                                return o.id==item.id ?$.extend({},o,item) : o;
                            })
                            this.render();
                        },

                        removeItem:function(id,render){
                            var that=this;
                            this.data = this.data.filter(function(value,i){

                                var ok=value.id!=id;

                                if(!ok){
                                    delete that._keys[id];
                                }

                                return ok;
                            })

                            if(render!==false){
                                this.render();
                            }
                        }
                    };

                    var app=this;
                    $('[lottery-editor]').each(function(){
                        var $this=$(this);
                        var data=[];

                        var $script=$this.find('[type=config]');
                        if($script.length==1){
                            var initData =$script.remove().val();
                            var theData=JSON.parse(initData);
                            if(theData instanceof Array) data=theData;
                        }

                        $this.empty();

                        var le=new LotteryEditor(this,{
                            config:{
                                max:12,min:6
                            },
                            data:data,
                            template:template.compile(document.getElementById('lottery/editor').innerHTML),
                            actions:{
                                'add':function(){
                                    app.editLottery('lottery/add').then(function(item){
                                        le.addItem(item);
                                    })
                                },
                                'edit':function(data){
                                    app.editLottery('lottery/edit',data).then(function(item){
                                        le.updateItem(item);
                                    })
                                },
                                'remove':function(id){
                                    le.removeItem(id);
                                }
                            }
                        })
                        console.info(le);
                    })
                },

                // 编辑中奖项
                editLottery:function(id , data){
                    var app=this;
                    var dtd = $.Deferred();
                    var title=document.getElementById(id).title;
                    var content=template(id,data);
                    var idialog=dialog({
                        id : id,
                        zIndex: 5,width:420,
                        padding:"0 20px",
                        button:[
                            {
                                id:"cancel",value:"取消"
                            },
                            {
                                id:"ok",value:"确定",
                                autofocus:true,
                                callback:function(){
                                    var $form=this.getContent().find("form");
                                    $form.checkForm({
                                        onSuccess:function(){
                                            var data=$.deParam($form.serialize());
                                            dtd.resolve(data);
                                            idialog.remove();
                                        },
                                        onFail:function(e){
                                            alert(e);
                                            e.focus();
                                        }
                                    })
                                    return false;
                                }
                            }
                        ]
                    })
                    idialog.title(title).content(content).showModal();
                    return dtd;
                }
            });
            
    		App.init();
    	
        })
   </script>
    </body>
</html>